﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Authorisation;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Spark.AspNetCore;
using Spark.Ocelot.Remote;
using Spark.ServiceDiscovery.Extensions;
using Spark.ServiceDiscovery.Remote.Extensions;
using System.Linq;
using Ocelot.Configuration.File;

namespace Spark.Samples.ApiGateway
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSpark(
                builder =>
            {
                builder.AddServiceDiscovery(x => x.UseRemote(Configuration));
            });

            //services.Configure<FileConfiguration>(Configuration.GetSection("SamplesGatewayConfig:OcelotConfig"));

            //services.AddOcelot(new ConfigurationBuilder()
            //        .AddJsonFile("ocelot.json")
            //        .Build())
            //.AddRemoteServiceDiscovery();

            services
                .AddOcelot()
                .AddRemoteServiceDiscovery()
            .AddConfigStoredInRemote("SamplesGatewayConfig:OcelotConfig");
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            // 使用网关
            await app.UseOcelot();
            app.UseMvc();
        }
    }
}